import { login, sysProfile, sysUser } from '@/api/user'
import router from '@/router'
import { getToken, setToken } from '@/utils/auth'
import asyncRouter from '@/router/modules/index.js'
import { constantRoutes } from '@/router'
import { resetRouter } from '@/router'
const state = {
  token: getToken() || '',
  userInfo: ''
}
const mutations = {
  setToken(state, value) {
    state.token = value
    setToken(value)
  },
  setUserInfo(state, value) {
    state.userInfo = value
  },
  logout(state) {
    state.token = ''
    setToken('')
    state.userInfo = ''
    resetRouter()
  }
}
const actions = {
  async toLogin({ commit }, value) {
    const res = await login(value)
    commit('setToken', res.data)
    console.log(res)
  },
  async getUserInfo({ commit }) {
    const res = await sysProfile()
    const res2 = await sysUser(res.data.userId)
    commit('setUserInfo', { ...res.data, ...res2.data })
    const newArr = asyncRouter.filter((item) => {
      return state.userInfo.roles.menus.includes(item.name)
    })
    newArr.push({ path: '*', redirect: '/404', hidden: true })
    console.log('newArr', newArr)
    commit('routes/setRoutesList', [...constantRoutes, ...newArr], {
      root: true
    })
    router.addRoutes(newArr)
    console.log('个人用户信息', res, res2)
  }
}
export default {
  namespaced: true,
  state,
  mutations,
  actions
}
